layui.define(['element', 'api', 'fast_config', 'resource_content'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'open_domain',
		$ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        resource_content = layui.resource_content
    ;

	var open_domain = function(opt) {
		this.option = opt;
	};


    /**
	 * Button start loading
	 * */
    open_domain.prototype.render = function(opt) {
		
		var option = {
			elem: opt.elem,
            // resource_content_settings: opt.resource_content_settings
            treeNode: opt.treeNode,
            viewMode: opt.viewMode,
            pearBody : opt.pearBody,
            amisData: opt.amisData,
            resource_tabs : opt.resource_tabs
		}

        render(option);


        return new open_domain(option);
	}

    function render(option){

        var grid;
        var path = option.treeNode.data.path;
        var colM = [];
        var metaName;


        var dateEditor = function (ui) {
            var $inp = ui.$cell.find("input"),
                grid = this,
                validate = function (that) {
                    var valid = grid.isValid({
                        dataIndx: ui.dataIndx,
                        value: $inp.val(),
                        rowIndx: ui.rowIndx
                    }).valid;
                    if (!valid) {
                        that.firstOpen = false;
                    }
                };

            //initialize the editor
            $inp
                .on("input", function (evt) {
                    validate(this);
                })
                .datepicker({
                    changeMonth: true,
                    changeYear: true,
                    showAnim: '',
                    dateFormat: 'yy-mm-dd',
                    onSelect: function () {
                        this.firstOpen = true;
                        validate(this);
                    },
                    beforeShow: function (input, inst) {
                        return !this.firstOpen;
                    },
                    onClose: function () {
                        this.focus();
                    }
                });
        }

        api.get({
            enableRootPath: true,
            type: "GET",
            url: "/resource",
            data: { 'path': path },
            async: false,
            dataType: "json",
            success: function (response) {
                metaName = response.name;

                $.each(response.fields, function(index, object){
                    colM[index] = {
                        title: object.name,
                        dataIndx: object.name,
                        width: 120,
                    }


                    if(object.primaryKey){
                        colM[index].editable = false
                        // colM[index].validations = [
                        //     { type: 'minLen', value: 1, msg: "Required" }
                        // ]
                    }

                    if(object.type === 'date'){
                        colM[index].dataType = 'date';
                        colM[index].format = 'yy-mm-dd'
                        colM[index].editor = {
                            type: 'textbox',
                            init: dateEditor
                        }
                    }else if(object.type === 'integer'){
                        colM[index].dataType = 'integer'
                    }
                })
            }
        });

        //called when save changes button is clicked.
        function saveChanges() {

            //attempt to save editing cell.
            if (grid.saveEditCell() === false) {
                return false;
            }

            if ( grid.isDirty() && grid.isValidChange({ focusInvalid: true }).valid ) {

                var changes = grid.getChanges({ format: "byVal" });

                //post changes to server
                api.post({
                    enableRootPath: true,
                    dataType: "json",
                    type: "POST",
                    async: true,
                    beforeSend: function (jqXHR, settings) {
                        grid.showLoading();
                    },
                    url: "/meta/" + metaName + "/batch",
                    // contextT
                    data: JSON.stringify(changes),
                    headers:{'Content-Type':'application/json;charset=utf8'},
                    success: function (changes) {
                        ////debugger;
                        grid.commit({ type: 'add', rows: changes.addList });
                        grid.commit({ type: 'update', rows: changes.updateList });
                        grid.commit({ type: 'delete', rows: changes.deleteList });

                        grid.history({ method: 'reset' });
                    },
                    complete: function () {
                        grid.hideLoading();
                    }
                });
            }
        }

        //获取url中的参数
        function getUrlParam(url, name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = url.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        }

        var obj = {
            hwrap: false,
            virtualX: true,
            rowBorders: false,
            trackModel: { on: true }, //to turn on the track changes.
            toolbar: {
                items: [

                    { type: 'button', icon: 'ui-icon-plus', label: '新增', listener: function () {
                            //append empty row at the end.
                            var rowData = {  }; //empty row
                            // var rowData = { ProductID: 34, UnitPrice: 0.2 }; //empty row
                            var rowIndx = grid.addRow( { rowData: rowData, checkEditable: true });
                            // var rowIndx = grid.addRow( { rowData:rowData, checkEditable: true });
                            grid.goToPage({ rowIndx: rowIndx });
                            grid.editFirstCellInRow({ rowIndx: rowIndx });
                        }
                    },
                    { type: 'separator' },
                    { type: 'button', icon: 'ui-icon-disk', label: '保存', cls: 'changes', listener: function () {
                            saveChanges();
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-cancel', label: '取消更改', cls: 'changes', listener: function () {
                            grid.rollback();
                            grid.history({ method: 'resetUndo' });
                        },
                        options: { disabled: true }
                    },
                    // { type: 'button', icon: 'ui-icon-cart', label: 'Get Changes', cls: 'changes', listener: function () {
                    //         var changes = grid.getChanges({ format: 'byVal' });
                    //         alert(changes);
                    //         if( console && console.log) {
                    //             console.log(changes);
                    //         }
                    //         alert("Please see the log of changes in your browser console.");
                    //     },
                    //     options: { disabled: true }
                    // },
                    { type: 'separator' },
                    { type: 'button', icon: 'ui-icon-arrowreturn-1-s', label: 'Undo', cls: 'changes', listener: function () {
                            grid.history({ method: 'undo' });
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-arrowrefresh-1-s', label: 'Redo', listener: function () {
                            grid.history({ method: 'redo' });
                        },
                        options: { disabled: true }
                    },
                    { type: 'button', icon: 'ui-icon-refresh', label: '刷新', listener: function () {
                            $(option.elem).pqGrid( "refreshDataAndView" );
                        }
                    },

                ]
            },
            scrollModel: {
                autoFit: true
            },
            swipeModel: { on: false },
            editor: {
                select: true
            },
            bootstrap: { on : false },
            height:'flex',
            title: "<b>"+metaName+"</b>",
            history: function (evt, ui) {
                var $tb = this.toolbar();
                if (ui.canUndo != null) {
                    $("button.changes", $tb).button("option", { disabled: !ui.canUndo });
                }
                if (ui.canRedo != null) {
                    $("button:contains('Redo')", $tb).button("option", "disabled", !ui.canRedo);
                }
                $("button:contains('Undo')", $tb).button("option", { label: 'Undo (' + ui.num_undo + ')' });
                $("button:contains('Redo')", $tb).button("option", { label: 'Redo (' + ui.num_redo + ')' });
            },
            colModel: colM,
            postRenderInterval: -1, //call postRender synchronously.
            pageModel: { type: "remote", rPP: 20 },
            create: function(){
                this.widget().pqTooltip();
            },
            dataModel:{
                location: "remote",
                dataType: "JSON",
                method: "GET",
                recIndx: "id",
                url: fast_config.api + "/meta/" + metaName,
                getData:function( dataJSON, textStatus, jqXHR ){
                    return { curPage: dataJSON.page.number, totalRecords: dataJSON.page.size, data: dataJSON._embedded.list };
                },
                beforeSend: function( jqXHR, settings ){
                    var url = settings.url;
                    var pq_curpage = getUrlParam(url, 'pq_curpage');
                    var pq_rpp = getUrlParam(url, 'pq_rpp');
                    if(pq_curpage){
                        url += '&page=' + pq_curpage;
                    }
                    if(pq_rpp){
                        url += '&size=' + pq_rpp;
                    }

                    settings.url = url;
                }
            },
        };
        grid = pq.grid( option.elem, obj );

        // $(option.elem).pqGrid( "refreshDataAndView" );

        // $(option.elem).pqGrid( "option", "height", '100%+40' );
        // $(window).resize(function() {
        //     $(option.elem).pqGrid( "option", "height", '100%+40' );
        // });
    }

    exports(MOD_NAME, new open_domain());
});
